<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <el-select v-model="listQuery.sid" class="filter-item" style="width: 130px;" filterable clearable :loading="loading" placeholder="选择区服">
        <el-option v-for="item in serverList" :key="item.sid" :label="item.name + '(' + item.sid + ')'" :value="item.sid">
        </el-option>
      </el-select>
      <el-select v-model="listQuery.db" class="filter-item" style="width: 130px;" filterable clearable placeholder="选择库">
        <el-option label="游戏日志库" value="server_log"></el-option>
        <el-option label="后台日志库" value="log_central"></el-option>
        <el-option label="入口库" value="game.conf"></el-option>
        <el-option label="后台库" value="mysql"></el-option>
      </el-select>
      <el-select v-model="listQuery.limit_type" class="filter-item" style="width: 130px;" filterable clearable placeholder="查询行类型">
        <el-option label="max(无limit限制)" value="max"></el-option>
        <el-option label="limit限制" value="limit"></el-option>
      </el-select>
      <br>
      <el-input v-model="listQuery.sql" type="textarea" :rows="28" style="width: 50%;" placeholder="请输入sql内容"></el-input>
      <el-input v-model="listQuery.code" type="textarea" :rows="28" style="width: 50%;" placeholder="请输入逻辑内容"></el-input>
      <el-upload
        ref="upload"
        class="filter-item"
        action="#"
        :headers="header"
        :limit="1"
        :file-list="fileList"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
      >
        <el-button type="success" icon="el-icon-upload2">文件</el-button>
      </el-upload>
      <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter('')">搜索</el-button>
      <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter('log')">记录标签</el-button>
      <el-button :loading="downloadLoading" type="primary" icon="el-icon-download" class="filter-item" @click="handleDownload()">导出</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border height="725">
      <template>
        <el-table-column v-for="column in columns" :key="column.prop" :label="column.label" :prop="column.prop" :width="column.width" :align="column.align || 'center'" />
      </template>
    </el-table>
    <div>
      <!-- 弹出的内容 -->
      <el-dialog title="备注" :visible.sync="dialogFormVisible" :close-on-click-modal="false">

        <el-form ref="dataForm">
          <el-form-item v-if="listQuery.history_id" label="是否替换">
            <el-switch v-model="listQuery.replace" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#a3a7a5">
            </el-switch>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="listQuery.remark" type="textarea" :rows="5" placeholder="请输入标签内容">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleFilter('to_log')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getServerList, handleSql } from '@/api/ops'
import { objectMerge, deepClone } from '@/utils'

export default {
  name: 'DebugSql',
  components: {},
  props: {
    rowData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      fileList: [],
      header: {
        Authorization: this.$store.state.user.token
      },
      loading: false,
      listLoading: false,
      downloadLoading: false,
      serverList: [],
      formData: {
        file: null
      },
      listQuery: {
        sid: '',
        db: 'server_log',
        sql: 'select 1',
        type: '',
        code: '',
        replace: '0',
        limit_type: 'limit'
      },
      list: [],
      columns: [],
      dialogFormVisible: false
    }
  },
  created() {
    this.getServerList()
    const rowData = deepClone(this.rowData)
    if (rowData.id) {
      console.log('init rowData')
      this.listQuery.sql = rowData.content
      this.listQuery.code = rowData.code
      this.listQuery.db = rowData.db
      this.listQuery.sid = rowData.sid ? parseInt(rowData.sid) : ''
      this.listQuery.history_id = rowData.id
      console.log(rowData)
    }
  },
  methods: {
    handleFileChange(file, fileList) {
      console.log('handleFileChange')
      this.formData.file = file.raw
    },
    handleRemove(file, fileList) {
      console.log(file)
    },
    beforeUpload(file) {
      console.log(file)
    },
    async getServerList(params) {
      const query = params
      const res = await getServerList(query)
      this.serverList = res.data.items
      this.loading = false
    },
    remarkHandleConfirm() {
      this.getList()
    },
    handleFilter(type) {
      this.listQuery.type = type
      if (!this.listQuery.sql) {
        // this.$message.warning('请输入sql')
        // return
      }
      if (type === 'log') {
        console.log(type)
        this.dialogFormVisible = !this.dialogFormVisible
      } else if (type === 'to_log') {
        this.dialogFormVisible = !this.dialogFormVisible
        this.getList()
        this.$message({
          message: '标记成功',
          type: 'success'
        })
      } else {
        this.dialogFormVisible = false
        this.getList()
      }
    },
    getColumns(row) {
      const columns = []
      if (row) {
        const length = Object.getOwnPropertyNames(row).length
        console.log(length)
        const width = length < 10 ? '' : parseInt(2 / length * 100) + '%'
        console.log(width)
        //, width: width || ('' + (column.length * 10) + 'px')
        for (const column in row) {
          const row = { 'label': column, 'prop': column, align: 'center' }
          if (length > 10) {
            row.width = (column.length * 20) + 'px'
          }
          columns.push(row)
        }
      }
      return columns
    },
    async getList() {
      Object.keys(this.listQuery).forEach(key => {
        this.formData[key] = this.listQuery[key]
      })
      this.listLoading = true
      const res = await handleSql(this.formData, this.header)
      this.listLoading = false
      this.list = res.data.items
      this.columns = this.getColumns(this.list[0])
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        Object.keys(this.listQuery).forEach(key => {
          this.formData[key] = this.listQuery[key]
        })
        this.formData['export'] = 1
        handleSql(this.formData).then(response => {
          this.dlist = response.data.items
          const tHeader = this.getColumns(this.dlist[0]).filter(v => v['label']).map(v => v['label'])
          const data = this.dlist.map(v => tHeader.map(j => {
            return v[j]
          }))
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '查询结果'
          })
          this.downloadLoading = false
        })
      })
    }
  }
}
</script>

<style scoped>
.el-table {
  font-size: 14px;
}

.el-table td,
.el-table th {
  padding: 10px 0 !important;
}

.el-table th>.cell {
  padding-left: 10px;
  padding-right: 10px;
}

.el-table td {
  text-align: left !important;
}
</style>
